package cn.whdream.datastructure.stack;

/**
 * 
 * @author admin 个位数字计算器
 */
public class OnesPlacesCalculater {
	public static void main(String[] args) {
		String expression = "7+2*6-4";
		//String expression = "70+2*6-4";如何处理多维数组
		ArrayStack numStack = new ArrayStack(10);
		ArrayStack operStack = new ArrayStack(10);
		int num1 = 0;
		int num2 = 0;
		int oper;
		int res = 0;
		char ch;
		for (int i = 0; i < expression.length(); i++) {
			ch = expression.substring(i, i + 1).charAt(0);
			if (isOpertion(ch)) {
				if (!operStack.isEmpty()) {
					char head = (char) operStack.peek();
					boolean neadPop =needPopOpertion(head,ch);
					if(neadPop) {
						oper = operStack.pop();
						num1 = numStack.pop();
						num2 = numStack.pop();
						res = calculate(num1,num2,oper);
						numStack.add(res);
						operStack.add(ch);
					}else {
						operStack.add(ch);
					}
					
				}else {
					//为空则添加 ch
					operStack.add(ch);
				}
			}else {
				numStack.add(ch-48);
			}	
		}
		while (true) {
			//操作符栈为空，数字栈的最后一个就是结果
			if (operStack.isEmpty()) {
				break;
			}
			num1 = numStack.pop();
			num2 = numStack.pop();
			res = calculate(num1, num2, operStack.pop());
			numStack.add(res);
		}
		System.out.println(expression+"="+numStack.peek());
		numStack.list();
	}

	private static int calculate(int num1, int num2, int oper) {
		switch (oper) {
		case '+':
			return num1 + num2;
		case '-':
			return num2 - num1;
		case '*':
			return num1 * num2;
		case '/':
			return num2 / num1;	
		default:
			return 0;
		}
	
	}

	private static boolean needPopOpertion(char stackHead, char ch) {
		int headPriority = getPriority(stackHead);
		int chPriority = getPriority(ch);
		return chPriority <= headPriority;
	}

	private static int getPriority(char stackHead) {
		if (stackHead == '*' || stackHead == '/') {
			return 1;
		}else if (stackHead == '+' || stackHead == '-') {
			return 0;
		}
		return -1;
	}

	private static boolean isOpertion(char ch) {
		if (ch == '+'|| ch == '-' || ch == '*'|| ch == '/') {
			return true;
		}
		return false;
	}

}
